package cer.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import javax.crypto.Cipher;

import sun.misc.BASE64Encoder;

 

// 公钥加密，私钥解密示例程序
public class A {
 public static void main(String[] args) throws Exception {

  byte[] msg = "犯大汉天威者，虽远必诛！".getBytes("UTF8");     // 待加解密的消息
  
  String path = A.class.getResource("").getPath();
  
  // 获取证书的公钥
  CertificateFactory cff = CertificateFactory.getInstance("X509");
  FileInputStream fis1 = new FileInputStream(path+"www.server.com.cer"); // 证书文件
  Certificate cf = cff.generateCertificate(fis1);
  PublicKey pk1 = cf.getPublicKey();  
  fis1.close();

  //用公钥加密数据
  Cipher c1 = Cipher.getInstance("RSA");      // 定义算法：RSA
  c1.init(Cipher.ENCRYPT_MODE, pk1);           
  byte[] msg1 = c1.doFinal(msg);            // 加密后的数据
  
  // 获取证书的私钥——该私钥存在生成该证书的密钥库中 
  FileInputStream fis2 = new FileInputStream(path+"/www.server.com.p12");
  KeyStore ks = KeyStore.getInstance("pkcs12");         // 加载证书库
  char[] kspwd = "123456".toCharArray();          // 证书库密码
  char[] keypwd = "123456".toCharArray();          // 证书密码
  ks.load(fis2, kspwd);              // 加载证书
  PrivateKey pk2 = (PrivateKey)ks.getKey("www.server.com", keypwd);     // 获取证书私钥
  
  
  
  			BASE64Encoder base64 = new BASE64Encoder();
			FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\admin\\Desktop\\ca\\new\\pirvateKey222.pem"));

			// fos.write(certificate.getEncoded());
			// 生成（保存）cert文件 base64加密 当然也可以不加密
			base64.encodeBuffer(pk2.getEncoded(), fos);
			fos.close();
  
  fis2.close();
  
  //用私钥解密数据
  Cipher c2 = Cipher.getInstance("RSA");
  c2.init(Cipher.DECRYPT_MODE, pk2);
  byte[] msg2 = c2.doFinal(msg1);            // 解密后的数据
  
  // 打印解密字符串 - 应显示 犯大汉天威者，虽远必诛！
  System.out.println(new String(msg2,"UTF8"));        // 将解密数据转为字符串
 }
}
